import { _decorator, Component, resources, ImageAsset, Node, Prefab, instantiate, Button, Sprite, UIOpacity, Label, SpriteFrame } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EditorManage')
export class EditorManage extends Component {

    @property(Prefab)
    index: Prefab = null

    @property(Node)
    content: Node = null

    @property(Label)
    floor: Label = null

    @property(Sprite)
    map: Sprite = null

    current: number = 1

    private res: Map<string, string> = new Map()


    start() {
        this.initIndex()
    }

    update(deltaTime: number) {
        this.floor.string = `第 ${this.current} 层`
    }

    bclick(event) {
        const bg = event.node.getChildByName('Sprite').getComponent(UIOpacity)
        const pos = event.node.getPosition()
        const index = pos.x / 35 + '-' + pos.y / 35

        if (this.res.has(index)) {
            bg.opacity = 100
            this.res.delete(index)
        } else {
            this.res.set(index, '1')
            bg.opacity = 255
        }
    }

    sout() {
        const a = []
        this.res.forEach((v, k) => {
            a.push(k)
        })
        console.log(JSON.stringify(a))
    }

    clear() {
        this.res = new Map()
        this.content.removeAllChildren()
        this.initIndex()
    }

    initIndex() {
        for (let i = 0; i < 11; i++) {
            for (let j = 0; j < 11; j++) {
                const ci = instantiate(this.index)
                ci.setPosition(35 * i, 35 * j)
                var button = ci.getComponent(Button);
                button.node.on('click', this.bclick, this);
                this.content.addChild(ci)
            }
        }
    }

    preFloor() {
        this.current -= 1
        this.loadResource(`abg/${this.current}f`)
    }

    nextFloor() {
        this.current += 1
        this.loadResource(`abg/${this.current}f`)
    }

    loadResource(address: string) {
        resources.load(address, ImageAsset, (err, imageAsset) => {
            if (err) {
                return console.error("ImageAssert load failed, err:" + err.message);
            }
            this.map.spriteFrame = SpriteFrame.createWithImage(imageAsset);
        });
    }

}

